import { useEffect, useMemo, useState } from "react";
import { Button, Card, Drawer, Form, Input, Space, Select } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import sysPostService, { type PageListReq } from "@/api/services/system/postService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import type { SysPost } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";

const { TextArea } = Input;

export default function SysPostPage() {
    const [loading, setLoading] = useState(false);
    const [queryParams, setQueryParams] = useState<PageListReq>({
      postCode: undefined,
      postName: undefined,
      page: 1,
      pageSize: 10,
    });
    const [total, setTotal] = useState(0);
    const [list, setList] = useState<SysPost[]>([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [editingData, setEditingData] = useState<SysPost | null>(null);
    const [form] = Form.useForm();
    const [isView, setIsView] = useState(true);

    //动态设置表格高度
    const [tableScrollY, setTableScrollY] = useState(0);
    const PAGE_OFFSET_HEIGHT = 403;
    const updateTableHeight = () => {
      const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
      setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
    };

    // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
    useEffect(() => {
      updateTableHeight(); // 初始化
      window.addEventListener("resize", updateTableHeight);
      return () => window.removeEventListener("resize", updateTableHeight);
    }, []);

    const statusOptions = useDictionary("system_status");

    const columns: ColumnsType<SysPost> = [
    {
      title: "岗位编码",
      width: 120,
      key: "postCode",
      dataIndex: "postCode",
    },
    {
      title: "岗位名称",
      width: 120,
      key: "postName",
      dataIndex: "postName",
    },
    {
      title: "状态",
      width: 120,
      key: "status",
      dataIndex: "status",
      render: (_, record) => (
        <TableDictTag dictCode="system_status" value={record.status ?? ''}/>
      )
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: 'right',
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
    ];

    const [selectedValues, setSelectedValues] = useState<string[]>(() =>
        columns.filter((col) => col.key !== "operation").map((col) => col.key ? String(col.key) : ''),
    );

    // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
    const filteredColumns = useMemo(() => {
      return [
        ...columns.filter(
          (col) => selectedValues.includes(String(col.key)) || col.key === "operation",
        ),
      ].sort((a, b) => {
        const originalIndex = columns.findIndex((c) => c.key === a.key);
        const targetIndex = columns.findIndex((c) => c.key === b.key);
        return originalIndex - targetIndex;
        });
    }, [selectedValues]);

    //加载表格数据
    const fetchPageList = () => {
      setLoading(true);
      sysPostService.pageList(queryParams).then(res => {
        setList(res.records);
        setTotal(res.total);
      }).catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      }).finally(() => {
        setLoading(false);
      });
    };

    // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
    useEffect(() => {
      fetchPageList();
    }, [queryParams]);

    //选择其他页
    const handlePageChange = (newPage: number, newPageSize: number) => {
      setQueryParams((prev) => ({
        ...prev,
        page: newPage,
        pageSize: newPageSize,
      }));
    };

    //触发编辑按钮
    const handleEdit = (sysPost: SysPost) => {
      setEditingData(sysPost);
      form.setFieldsValue(sysPost);
      setDrawerVisible(true);
      setIsView(false);
    };

    //触发视图按钮
    const handleView = (sysPost: SysPost) => {
      setEditingData(sysPost);
      form.setFieldsValue(sysPost);
      setIsView(true);
      setDrawerVisible(true);
    };

    //提交表单数据
    const handleSubmit = async (values:  SysPost) => {
      try {
        setLoading(true);
      if (editingData) {
        await sysPostService.update({ ...values, id: editingData.id });
        toast.success("更新岗位信息成功");
      } else {
        await sysPostService.add(values);
        toast.success("创建岗位信息成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
      } catch (error) {
        toast.error(`保存失败: ${error.message}`);
      } finally {
        setLoading(false);
      }
    };

    const handleDrawerClose = () => {
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
    };

    const handleAdd = () => {
      setEditingData(null);
      form.resetFields();
      setDrawerVisible(true);
      setIsView(false);
    };

    const handleDelete = async () => {
      try {
        setLoading(true);
        await sysPostService.remove(selectedRowKeys);
        toast.success("删除岗位信息成功");
        setSelectedRowKeys([]);
        fetchPageList();
      } catch (error) {
        toast.error(`删除失败: ${error.message}`);
      } finally {
        setLoading(false);
      }
    };

    return (
      <>
        <Card className="mb-4">
          <Form
            layout="inline"
            onFinish={(values) => {
              setQueryParams((prev) => ({
                ...prev,
                ...values,
                page: 1,
              }));
            }}
          >
            <Form.Item name="postCode" label="岗位编码">
              <Input placeholder="请输入岗位编码" allowClear />
            </Form.Item>
            <Form.Item name="postName" label="岗位名称">
              <Input placeholder="请输入岗位名称" allowClear />
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">
                    查询
                </Button>
                <Button
                  className="ml-2"
                  onClick={() => {
                    setQueryParams({ page: 1, pageSize: 10 });
                  }}
                >
                重置
                </Button>
            </Form.Item>
            </Form>
        </Card>
        <div className="h-4" />
        <Card>
            <div className="flex justify-between mb-4">
                <div className="flex gap-2">
                    <Button type="primary" onClick={handleAdd}>
                        新增
                    </Button>
                    <Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
                    删除
                    </Button>
                </div>
                <TableToolbar
                        onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
                onSizeChange={setTableSize}
                columns={columns}
                selectedValues={selectedValues}
                onColumnChange={setSelectedValues}
                />
            </div>
            <Table
                rowKey="id"
                size={tableSize}
                scroll={{ x: "max-content", y: tableScrollY }}
                loading={loading}
                pagination={{
                    total,
                    current: queryParams.page,
                    pageSize: queryParams.pageSize,
                    onChange: handlePageChange,
                }}
                columns={filteredColumns}
                dataSource={list}
                rowSelection={{
                    type: "checkbox",
                    selectedRowKeys: selectedRowKeys,
                    onChange: (selectedKeys) => {
                        setSelectedRowKeys(selectedKeys as string[]);
                    },
                }}
            />
        </Card>
        <Drawer
            title={editingData ? "编辑岗位信息" : "新增岗位信息"}
            width={480}
            open={drawerVisible}
            onClose={handleDrawerClose}
            footer={
                <div className="flex justify-end gap-2">
                    <Button onClick={handleDrawerClose}>取消</Button>
                    {!isView && (
                    <Button type="primary" onClick={() => form.submit()}>
                    确定
                    </Button>
                    )}
                </div>
            }
        >
          <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
              <Form.Item
                name="postCode"
                label="岗位编码"
                rules={[
                  {
                    required: true,
                    message: '请填写岗位编码',
                  }
                ]}
              >
                <Input placeholder="请输入岗位编码" allowClear/>
              </Form.Item>
              <Form.Item
                name="postName"
                label="岗位名称"
                rules={[
                  {
                    required: true,
                    message: '请填写岗位名称',
                  }
                ]}
              >
                <Input placeholder="请输入岗位名称" allowClear/>
              </Form.Item>
              <Form.Item
                name="status"
                label="状态"
                initialValue="1"
              >
                <Select options={statusOptions}  allowClear/>
              </Form.Item>
              <Form.Item
                name="remark"
                label="备注"
              >
                <TextArea/>
              </Form.Item>
          </Form>
        </Drawer>
    </>
    );
}